/*
 * HospedajeNuevo.java
 *
 * Created on 21/10/2010, 01:16:20 AM
 */
package pe.edu.upla.lamerced.desk.view.hospedaje;

import java.util.Date;
import java.util.List;
import javax.swing.JDesktopPane;
import javax.swing.JOptionPane;
import pe.edu.upla.lamerced.Inicial;
import pe.edu.upla.lamerced.Utiles;
import pe.edu.upla.lamerced.bean.Habitacion;
import pe.edu.upla.lamerced.bean.Hospedaje;
import pe.edu.upla.lamerced.bean.Tipohabitacion;
import pe.edu.upla.lamerced.bean.Users;
import pe.edu.upla.lamerced.desk.view.Login;
import pe.edu.upla.lamerced.service.HabitacionService;
import pe.edu.upla.lamerced.service.HospedajeService;
import pe.edu.upla.lamerced.service.UsuarioService;

/**
 *
 * @author elvis
 */
public class HospedajeNuevo extends javax.swing.JInternalFrame {

   private JDesktopPane escritorio;
   private HospedajeService hospedajeService;
   private HabitacionService habitacionService;
   private UsuarioService usuarioService;
   private List<Tipohabitacion> listaTipoHabitacion;
   private List<Habitacion> listaHabitaciones;
   private List<Users> listaClientes;

   public JDesktopPane getEscritorio() {
      return escritorio;
   }
   public void setEscritorio(JDesktopPane escritorio) {
      this.escritorio = escritorio;
   }

   /** Creates new form HospedajeNuevo */
    public HospedajeNuevo() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnGrabaHospedaje = new javax.swing.JButton();
        btnCancelaHospedaje = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        txtFecha = new javax.swing.JTextField();
        txtdias = new javax.swing.JTextField();
        cbTipoHabitacion = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        cbHabitacion = new javax.swing.JComboBox();
        jLabel11 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        cbCliente = new javax.swing.JComboBox();

        setClosable(true);
        setTitle("Registrar Hospedaje");

        btnGrabaHospedaje.setText("Grabar");
        btnGrabaHospedaje.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGrabaHospedajeActionPerformed(evt);
            }
        });

        btnCancelaHospedaje.setText("Cancelar");
        btnCancelaHospedaje.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelaHospedajeActionPerformed(evt);
            }
        });

        jLabel4.setText("Tipo de Habitacion");

        txtFecha.setEditable(false);

        cbTipoHabitacion.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cbTipoHabitacion.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbTipoHabitacionItemStateChanged(evt);
            }
        });

        jLabel9.setText("Habitacion");

        cbHabitacion.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel11.setText("Dias");

        jLabel10.setText("Fecha");

        jLabel3.setText("Cliente");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel9)
                            .addComponent(jLabel10)
                            .addComponent(jLabel11)
                            .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(16, 16, 16)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cbHabitacion, javax.swing.GroupLayout.Alignment.TRAILING, 0, 200, Short.MAX_VALUE)
                            .addComponent(txtFecha, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)
                            .addComponent(txtdias, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)
                            .addComponent(cbTipoHabitacion, javax.swing.GroupLayout.Alignment.TRAILING, 0, 200, Short.MAX_VALUE)
                            .addComponent(cbCliente, 0, 200, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(63, 63, 63)
                        .addComponent(btnGrabaHospedaje)
                        .addGap(34, 34, 34)
                        .addComponent(btnCancelaHospedaje)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(cbCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cbTipoHabitacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cbHabitacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtdias, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnGrabaHospedaje)
                    .addComponent(btnCancelaHospedaje))
                .addContainerGap(26, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelaHospedajeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelaHospedajeActionPerformed
       // TODO add your handling code here:
       HospedajeLista form = new HospedajeLista();
       form.setEscritorio(escritorio);
       escritorio.add(form);
       form.preLoadFormHospLst();
       form.setVisible(true);
       this.dispose();
    }//GEN-LAST:event_btnCancelaHospedajeActionPerformed

    private void btnGrabaHospedajeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGrabaHospedajeActionPerformed
      Hospedaje hospedaje=null;
        try {
            hospedaje = new  Hospedaje();
            if(cbCliente.getSelectedIndex()!=-1){
               hospedaje.setUsersByIdUsuarioCli(listaClientes.get(cbCliente.getSelectedIndex()));
            }else{
               JOptionPane.showMessageDialog(this, "No ha seleccionado a ningun cliente");
               return;
            }
            if(cbHabitacion.getSelectedIndex()==-1){
               JOptionPane.showMessageDialog(this, "No ha seleccionado a ninguna habitacion");
               return;
            }
            Users ulogin = Login.getUserLogin();
            hospedaje.setFecAlquiler(Utiles.stringToDate(txtFecha.getText(), Utiles.FORMATO_FECHA_CORTA));
            hospedaje.setDiasreserva(Integer.parseInt(txtdias.getText()));
            hospedaje.setUsersByIdUsuarioEmp(ulogin);
            Habitacion hab = listaHabitaciones.get(cbHabitacion.getSelectedIndex());
            Hospedaje rsertmp = hospedajeService.obtenerReservaExacta(txtFecha.getText(),hab.getIdhabitacion().toString());
            if( rsertmp != null){
               if(!rsertmp.getUsersByIdUsuarioCli().getUsername().equals(hospedaje.getUsersByIdUsuarioCli().getUsername())){
                  JOptionPane.showMessageDialog(this, "Ya esta reservada por otro cliente en esa fecha. No se puede realizar el hospedaje");
                  return;
               }
            }
            if( hospedajeService.obtenerHospedajeExacto(txtFecha.getText(),hab.getIdhabitacion().toString()) != null){
               JOptionPane.showMessageDialog(this, "Ya esta alquilada en esta fecha");
               return;
            }
                hab.setEstado(2);
                hospedaje.setEstado(2);
                hospedaje.setHabitacion(hab);
                hospedajeService.registrarHospedaje(hospedaje);
                System.out.println("id hospedaje = " + hospedaje.getIdhospedaje() );
              //  hospedaje = hospedajeService.obtenerHospedaje(hospedaje.getIdhospedaje());

           HospedajeLista form = new HospedajeLista();
           form.setEscritorio(escritorio);
           escritorio.add(form);
           form.preLoadFormHospLst();
           form.setVisible(true);
           this.dispose();

        } catch (Exception e) {
            e.printStackTrace();
             JOptionPane.showMessageDialog(this, e.getMessage());
        }
      
    }//GEN-LAST:event_btnGrabaHospedajeActionPerformed

    /**
     * No debe traer las habitaciones que esten ahorita alquiladas (en hospedaje)
     * ya que solo se hace el hospedaje en la fecha actual, no ha futuro
     * @param evt
     */
    private void cbTipoHabitacionItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbTipoHabitacionItemStateChanged
       if(cbTipoHabitacion.getSelectedIndex() != -1){
          int tip = cbTipoHabitacion.getSelectedIndex();
          Habitacion hab = new Habitacion();
          hab.setEstado(0);
          hab.setTipohabitacion(listaTipoHabitacion.get(tip));
          cbHabitacion.removeAllItems();
          listaHabitaciones = habitacionService.listaHabitacionessinEstado(hab);
          for(Habitacion habitacion : listaHabitaciones){
             cbHabitacion.addItem(habitacion.getNumero());
          }
       }
}//GEN-LAST:event_cbTipoHabitacionItemStateChanged



    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelaHospedaje;
    private javax.swing.JButton btnGrabaHospedaje;
    private javax.swing.JComboBox cbCliente;
    private javax.swing.JComboBox cbHabitacion;
    private javax.swing.JComboBox cbTipoHabitacion;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JTextField txtFecha;
    private javax.swing.JTextField txtdias;
    // End of variables declaration//GEN-END:variables


   public void cargaInicial(){
      try {
         if(hospedajeService==null){hospedajeService = (HospedajeService) Inicial.getFactory().getBean("hospedajeService");}
         if(usuarioService==null){usuarioService= (UsuarioService) Inicial.getFactory().getBean("usuarioService");}
         if(habitacionService==null){habitacionService = (HabitacionService)Inicial.getFactory().getBean("habitacionService");}
         cbTipoHabitacion.removeAllItems();
         listaTipoHabitacion =  habitacionService.listaTipoHabitacion();
         for(Tipohabitacion th : listaTipoHabitacion){
            cbTipoHabitacion.addItem(th.getNombre());
         }
         listaClientes = usuarioService.listaClientes();
         cbCliente.removeAll();
         for(Users cli : listaClientes){
            cbCliente.addItem(cli.getNombrecompleto());
         }
         txtFecha.setText(Utiles.dateToString(new Date(), "dd/MM/yyyy"));
      } catch (Exception e) {
         System.out.println(e.getMessage());
      }

   }



}
